package org.exeed.controller;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.exeed.aop.tag.Auth;
import org.exeed.bean.ResultBean;
import org.exeed.entity.FileEntity;
import org.exeed.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

//@CrossOrigin
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${file.path}")
    private String filepath = "temp/";


    @Value("${file.tmp}")
    private String tmpPath = "";

    @Autowired
    private ResourceService resourceService;

    private static String VIDEO_COVER_PATH = "video/cover/";

    private static String VIDEO_PATH = "video/";

    private static String IMAGE_PATH = "image/";

    private static String PDF_PATH = "pdf/";


    /**
     * 处理文件上传
     */
    @Auth
    @PostMapping(value = "/upload")
    public ResultBean uploading(@RequestParam("file") MultipartFile file) {


        FileEntity fileEntity = new FileEntity();

        File targetFile = new File(tmpPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        fileEntity.setFilename(file.getOriginalFilename());
        fileEntity.setActive(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        fileEntity.setUuid(UUID.randomUUID().toString());
        try (FileOutputStream out = new FileOutputStream(tmpPath + fileEntity.getUuid() + fileEntity.getActive())) {
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败!");
            return ResultBean.defeated();
        }
        log.info("文件上传成功!");

        fileEntity.setRealName(fileEntity.getUuid()+fileEntity.getActive());

        fileEntity.setTmpUrl(resourceService.getResourceUrl()+"temp/"+  fileEntity.getUuid() + fileEntity.getActive());

        return ResultBean.succeed(fileEntity);
    }

//    @Auth
    @GetMapping("/download/{type}/{filename}")
    public void downLoad(HttpServletResponse response, @PathVariable(value="type") String type, @PathVariable("filename") String filename) throws UnsupportedEncodingException {
        String fp = "";

        if (type.equals("video") ){
            fp = filepath + VIDEO_PATH +filename;
        }

        if (type.equals("image") ){
            fp = filepath + IMAGE_PATH +filename;
        }
        if (type.equals("pdf") ){
            fp = filepath + PDF_PATH +filename;
        }

        File file = new File(fp);
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8").replaceAll("\\+", ""));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


//    @GetMapping("/tmpFiles")
//    public ResultBean tmpFiles(@RequestParam("size") Integer size, @RequestParam("page") Integer page) {
//        File folder = new File(tmpPath);
//        String[] files = folder.list();
//        int pageSize = 10; // 每页显示的文件数
//        int pageNum = files.length / pageSize; // 分页数量
//
//        int start = (page - 1) * pageSize;
//        int end = Math.min(page * pageSize, files.length);
//
////        String[] pageFiles = Arrays.copyOfRange(files, start, end);
//    }
}
